import { CheckCircleFilled, MinusCircleFilled, PlusCircleFilled } from '@ant-design/icons';
import { Divider } from 'antd';
import { CSSProperties, useMemo, useState } from 'react';
import { udp, useUpdateEffect, useDraggableSort } from '@cscec/udp-ui';
import styles from './index.less';
import React from 'react';

const iconStyle: CSSProperties = {
  display: 'flex',
  background: '#fff',
  borderRadius: 14,
  position: 'absolute',
  top: 0,
  right: 2,
  zIndex: 11,
  cursor: 'pointer',
};

const getIconUrl = (funcIcon: string) => (funcIcon?.indexOf('http') === 0 ? funcIcon : udp.getHttpUrl(`/minio/${funcIcon}`));

const CommonFunctionBox = (props: { title: any; list: any; type: any; handleCheck: any; }) => {
  const {
    title, list, handleCheck, type,
  } = props;
  return (
    <div className={styles.box}>
      <div className={styles.title}>{title}</div>
      <div className={styles.content}>
        {list.map((item: { id: any; funcName?: any; funcIcon?: any; useFlg?: any; }) => (
          <CommonFunctionItem key={item.id} data={item} handleCheck={handleCheck} type={type} />
        ))}
      </div>
    </div>
  );
};
const CommonFunctionItem = ({ data, type, handleCheck }: any) => (
  <div className={styles.item}>
    <div className={styles.icon}>
      <img className={styles.img} src={getIconUrl(data.funcIcon)} />
      <div style={iconStyle}>
        {type === 'inUse' ? (
          <MinusCircleFilled style={{ color: '#CFCECE' }} onClick={() => handleCheck(data.id, 0)} />
        ) : data.useFlg ? (
          <CheckCircleFilled style={{ color: '#3BCC89' }} />
        ) : (
          <PlusCircleFilled style={{ color: '#CFCECE' }} onClick={() => handleCheck(data.id, 1)} />
        )}
      </div>
    </div>
    <div className="nowrap">{data.funcName}</div>
  </div>
);

export function Content({ dataRef }: { dataRef: any }) {
  const [list, setList] = useState<any>(dataRef.current.list);
  const [inUseList, listGroupByApp] = useMemo(() => {
    const result: any[] = [];
    const map = new Map();
    list.forEach((item: any, index: any) => {
      item.__index__ = index;
      if (item.useFlg === 1) {
        result.push(item);
      }
      if (!map.has(item.moduleCode)) {
        map.set(item.moduleCode, {
          key: item.moduleCode,
          label: item.moduleName,
          list: [],
        });
      }
      map.get(item.moduleCode).list.push(item);
    });

    return [result, [...map.values()]];
  }, [list]);
  const handleCheck = (id: any, useFlg: any) => {
    setList((list: any[]) => list.map((item: { id: any; }) => (item.id === id ? { ...item, useFlg } : item)));
  };

  useUpdateEffect(() => {
    dataRef.current.updateList = list;
  }, [list]);

  return (
    <div style={{ padding: 24 }}>
      <DragBox title="已添加" useList={inUseList} type="inUse" handleCheck={handleCheck} setList={setList} />
      <Divider />
      {listGroupByApp.map((listGroup: any) => (listGroup.list?.length ? (
        <CommonFunctionBox
          key={listGroup.key}
          title={listGroup.label}
          list={listGroup.list}
          type="inGroup"
          handleCheck={handleCheck}
        />
      ) : null))}
    </div>
  );
}

function DragBox(props: any) {
  const {
    title, useList, handleCheck, setList,
  } = props;
  const { SortContainer, SortElement } = useDraggableSort();
  const onSortEnd = ({ oldIndex, newIndex }: any) => {
    console.log(oldIndex, newIndex);

    if (oldIndex !== newIndex) {
      setList((preArr: any) => {
        const item = preArr.splice(oldIndex, 1)[0];
        preArr.splice(newIndex, 0, item);
        return [...preArr];
      });
    }
  };

  const shouldCancelStart = (e: any) => udp.closest(e.target, (el) => el.dataset.key === 'cancel-sort');

  return (
    <div className={styles.box}>
      <div className={styles.title}>{title}</div>
      <SortContainer axis="xy" lockAxis="xy" shouldCancelStart={shouldCancelStart} onSortEnd={onSortEnd}>
        <div style={{
          display: 'flex', flexWrap: 'wrap', width: 944, overflow: 'auto', position: 'relative',
        }}
        >
          {useList.map((item: any) => (
            <SortElement key={item.id} index={item.__index__}>
              <div style={{
                width: 188, zIndex: 1001, display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center',
              }}
              >
                <div style={{
                  padding: 8, width: 74, height: 74, position: 'relative',
                }}
                >
                  <img style={{ width: '100%', height: '100%' }} src={getIconUrl(item.funcIcon)} />
                  <div data-key="cancel-sort" style={iconStyle} onClick={() => handleCheck(item.id, 0)}>
                    <MinusCircleFilled style={{ color: '#CFCECE' }} />
                  </div>
                </div>
                <div className="nowrap">{item.funcName}</div>
              </div>
            </SortElement>

          ))}
        </div>
      </SortContainer>
    </div>
  );
}
